import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2022/3/16
 * \* Time: 16:02
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class TestJDBCWork {

    public static void main(String[] args) throws SQLException, ParseException {
        //1.创建数据库
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/ebook?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");

        //2.连接数据库
        Connection connection = dataSource.getConnection();
//        //3.输入信息
//        Scanner scanner = new Scanner(System.in);
//        System.out.println("请输入书本的id：");
//        int book_id = scanner.nextInt();
//        System.out.println("请输入学生的id：");
//        int student_id = scanner.nextInt();
//        System.out.println("请输入借出日期：");

//        SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date time1 = format0.parse(scanner.nextLine());
//        System.out.println(time1.getTime());
//
//        String str1 = scanner.nextLine();
//        System.out.println("请输入归还日期：");
//        String str2 = scanner.nextLine();

        //4.操作数据库
        String sql = "insert into borrow_info(book_id, student_id," +
                " start_time, end_time) select b.id,s.id,?,?" +
                " from book b,student s where b.name=? and s.name=?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setTimestamp(1, getTimestamp("2019-09-25 17:50:00"));
        statement.setTimestamp(2, getTimestamp("2019-10-25 17:50:00"));
        statement.setString(3, "诗经");
        statement.setString(4, "貂蝉");
        System.out.println(statement);



        //5.执行sql
        int ret = statement.executeUpdate();
        System.out.println(ret);

        statement.close();
        connection.close();
    }

    static Timestamp getTimestamp(String dateString) {
        try {
            // 年-月-日 小时:分钟:秒
            java.util.Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateString);
            return new java.sql.Timestamp(date.getTime());
        } catch (ParseException e) {
            throw new RuntimeException("日期格式化错误：" + dateString, e);
        }
    }
}
